import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  if (store.getters.token) { // 判断是否有token
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        // get user info
        // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
        const user = await store.dispatch('user/getInfo')
        // generate accessible routes map based on roles
        const accessRoutes = await store.dispatch('permission/generateRoutes', user.roles)
        console.log(accessRoutes);

        router.options.routes = store.getters.permission_routes

        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        console.log(store)
        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({ ...to, replace: true })

        // store.dispatch('user/getInfo', store.getters.token).then(res => { // 拉取info
        //   const role = res.userRole;
        //   store.dispatch('permission/generateRoutes', role).then(() => { // 生成可访问的路由表
        //     router.options.routes = store.getters.addRouters
        //     router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
        //     next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        //   })
        //   next({ path: '/' });
        // }).catch(err => {
        //   console.log(err);
        // });
      } else {
        next() //当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next();
    } else {
      next('/login'); // 否则全部重定向到登录页
    }
  }
});



router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
